<?php
class RegisterService
{
	/**
	 * 注册
	 * @Author   Leikes
	 * @DateTime 2016-01-29T17:46:00+0800
	 * @param    array                   $data 用户信息集合
	 * @return   exception                        [code,message]
	 */
	public function register($data)
	{
		try
		{
			//调用校验方法
			$this->verifyRegisterInfo($data);
			DB::transaction(function() use($data)
			{
				//用户注册
				$user=new User;
				$user->email    =$data['email'];
				$user->password =Hash::make($data['password']);

				if(!empty($data['register_number']))
				{
					$serverinfo=Serverinfo::where('register_number','=',$data['register_number']);
					$serverinfo->is_use  =true;
					$user->is_activation =true;
					$user->usergroup_id  =$serverinfo->usergroup_id;
					$serverinfo->save();
				}
				else
				{
					$user->usergroup_id=Config::get('systemConfig.user_group_id.free_users_group');
					$user->is_activation=false;
					$this->sendMail($data);
				}
				$user->save();

				//用户信息
				$user=User::where('email','=',$data['email'])->first();
				$userId=$user->user_id;
				$userinfo=new Userinfo;
				$userinfo->user_id      =$userId;
				$userinfo->surname      =$data['surname'];
				$userinfo->given_name   =$data['given_name'];
				$userinfo->phone        =$data['phone'];
				$userinfo->title        =$data['title'];
				$userinfo->company_name =$data['company_name'];
				$userinfo->address      =$data['address'];
				$userinfo->departmen    =$data['departmen'];
				$userinfo->city         =$data['city'];
				$userinfo->zip_code     =$data['zip_code'];
				$userinfo->save();

				$userRole=new User_role;
				if(!empty($data['role_id']))
				{
					$userRole->role_id=$data['role_id'];
				}
				else
				{
					$userRole->role_id=Config::get('systemConfig.system.role_id.researcher');
				}
				$userRole->user_id=$userId;
				$userRole->save();
			});
			
			throw new NormalException;
		}
		catch(UsernameIsNullException $e)
		{
			return $e;
		}
		catch(PasswordIsNullException $e)
		{
			return $e;
		}
		catch(FieldValueAuthException $e)
		{
		}
		catch(RegisterNumberException $e)
		{
			return $e;
		}
			return $e;
		catch(SendEmailException $e)
		{
			return $e;
		}
		catch(NormalException $e)
		{
			return $e;
		}
	}



	/**
	 * 校验注册信息
	 * @Author   Leikes
	 * @DateTime 2016-01-28T17:29:39+0800
	 * @param    array                   $data 用户注册信息
	 * @throw    exception
	 */
	private function verifyRegisterInfo($data)
	{
		$rules=[
			'email'        =>'required|email|unique:users,email',
			'password'     =>'required|in:'.$data['confirm_password'],
			'surname'      =>'required',
			'given_name'   =>'required',
			'phone'        =>'required|digits:11',
			'title'        =>'required',
			'company_name' =>'required',
			'address'      =>'required',
			'departmen'    =>'required',
			'city'         =>'required',
			'zip_code'	   =>'required'
		];
		// dd($rules);
		$validation = Validator::make($data,$rules);
		if( $validation->fails() )
		{
			throw new FieldValueAuthException( $validation->messages()->first() );
		}
		if(!empty($data['register_number']))
		{
			$rules=[
				'register_number' =>'alpha_num|max:16|min:16|exists:serverinfos,register_number,is_use,0'
			];
			$validation = Validator::make($data,$rules);
			if( $validation->fails() )
			{
				throw new RegisterNumberException( $validation->messages()->first() );
			}
		}
		if(!empty($data['role_id']))
		{
			$rules=[
				'role_id' =>'exists:roles,role_id'
			];
			$validation = Validator::make($data,$rules);
			if( $validation->fails() )
			{
				throw new FieldValueAuthException( $validation->messages()->first() );
			}
		}
		
	}



	/**
	 * 发送邮件
	 * @Author   Leikes
	 * @DateTime 2016-01-29T14:30:17+0800
	 * @param    array                   $data 用户注册信息
	 * @return   [type]                         [description]
	 */
	private function sendMail($data)
	{
		try
		{
			$admin=$this->findAllAdmin();
			Mail::send('emails.register.RegosterEMail', $data, function($message) use($data,$admin)
			{
				foreach($admin as $value){		
					$message->to($value->email)->subject('有一个客户注册中央随机系统,请登录到系统生成注册序列号,返回给用户');
				}   
			});
		}
		catch(Exception $e)
		{
			throw new SendEmailException;
		}
		
	}


	/**
	 * 查找出所有管理员权限的用户
	 * @Author   Leikes
	 * @DateTime 2016-01-29T16:08:47+0800
	 * @return   Object                   返回所有管理员的对象
	 */
	private function findAllAdmin()
	{
		$admin=Role::find(Config::get('systemConfig.system.role_id.system_admin'))->users()->get();
		return $admin;
	}


	/**
	 * 查找除去系统管理员以外的权限用于下拉菜单
	 * @Author   Leikes
	 * @DateTime 2016-01-29T17:43:53+0800
	 * @return   Object                   权限结果集
	 */
	public function findAllRole()
	{
		$roles=Role::where('role_id','!=',Config::get('systemConfig.system.role_id.system_admin'))->get();
		return $roles;
	}
}
?>